extends Node2D

@export var min_spawn_rock_time:float = 1.0
@export var max_spawn_rock_time:float = 2.0
@onready var plane:CharacterBody2D = %plane
@onready var game_form: Control = %GameForm
@onready var game_state_machine = %GameStateMachine

var s_rock:PackedScene = preload("res://src/entity/rock.tscn")
var s_plane:PackedScene = preload("res://src/entity/plane.tscn")

var timer:Timer = Timer.new()
var score_timer:Timer = Timer.new()
var current_score:int = 0

func _ready():
	game_state_machine.launch()
	retry_game()

## 初始化游戏
func init_game():
	pass
	
## 游戏准备
func ready_game():
	pass

# 开始戏，初始化态
func retry_game():
	# 给定时器绑定事件
	timer.timeout.connect(_on_timer_timeout)
	# 设置定时器超时时间，取随机值
	timer.wait_time = randf_range(min_spawn_rock_time,max_spawn_rock_time)
	self.add_child(timer)
	timer.one_shot = true
	# 开启定时器
	timer.start()

	# 设置加分时器
	score_timer.timeout.connect(_on_score_timer_timeout)
	score_timer.wait_time = 1
	self.add_child(score_timer)
	score_timer.start()

	# 始化化游戏分数
	current_score = 0
	game_form.update_score_display(current_score)

	# 隐藏失败页面
	game_form.retry_game()

	# 消暂停
	get_tree().paused = false


func _process(delta):
	# 如果飞机不存在，则创建
	if not plane:
		plane = s_plane.instantiate()
		plane.position = Vector2(100,165)
		self.add_child(plane)
	# 飞机超出上下边界游戏结束
	if plane.position.y <= 0 or plane.position.y >= get_viewport_rect().size.y:
		game_over()

# 计时器超时后触发
func _on_timer_timeout():
	spawn_rock()
	timer.wait_time = randf_range(min_spawn_rock_time,max_spawn_rock_time)
	timer.start()

# 创建障碍物
func spawn_rock():
	# 创建场景
	var rock:Node2D = s_rock.instantiate()
	# 为场景绑定信号，监听撞击事件
	rock.rock_entered.connect(_on_rock_entered)

	# 设置场景位置，随机出现在上下位置
	var random = randi_range(0,1)
	if random == 0:
		rock.position = Vector2(640,randi_range(240,352))
	else:
		# 旋转180°
		rock.rotation_degrees = 180
		rock.position = Vector2(640,randi_range(-32,40))

	# 挂载到主场景
	self.add_child(rock)

# 撞击逻辑处理
func _on_rock_entered():
	game_over()

# 游戏结束逻辑
func game_over():
	# 暂停游戏
	get_tree().paused = true
	# 销毁飞机
	plane.queue_free()
	# 障碍物销毁
	for rock in get_tree().get_nodes_in_group("rock"):
		rock.queue_free()
	# 游戏结束，显示结束页面
	game_form.game_over()


# 分数计时器超时处理
func _on_score_timer_timeout():
	current_score += 1
	game_form.update_score_display(current_score)


# 游戏退出
func _on_game_form_quit_pressed():
	get_tree().quit()

# 游戏重试
func _on_game_form_retry_pressed():
	retry_game()
